package com.enqualcomm.kids.mvp.bluetouch;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;


import java.util.concurrent.TimeUnit;

import common.utils.MyLogger;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.subjects.BehaviorSubject;


/**
 * Created by yinzhiqun on 2016/2/22.
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class BluetouchManager {
    boolean isSupportBLE;
    boolean isScanning;
    Context context;
    BluetoothAdapter mBluetoothAdapter;
    Subscription timmerSubscription;
    BehaviorSubject<BluetoothDevice> behaviorSubject;

    public BluetouchManager(Context context) {
        this.context = context;
        this.isSupportBLE = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
    }

    /**
     * 扫描蓝牙设备
     */
    public Observable<BluetoothDevice> getRemoteDevices(){
        this.behaviorSubject = BehaviorSubject.create();
        if (isSupportBLE()){
            scanDevicesBLE();
        }else{
            //不支持低功耗蓝牙
            behaviorSubject.onError(new Exception("设备不支持BLE"));
        }

        return behaviorSubject.observeOn(AndroidSchedulers.mainThread()).doOnUnsubscribe(new Action0() {
            @Override
            public void call() {
                if (timmerSubscription !=null&&!timmerSubscription.isUnsubscribed()){
                    timmerSubscription.unsubscribe();
                }
                if (isScanning){
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    isScanning = false;
                    MyLogger.jLog().i("手动停止扫描");
                }
            }
        });
    }

    /**
     * 用户打开蓝牙后，重新开始扫描
     */
    public void scanDevices(){
        if (isSupportBLE()) {
            scanDevicesBLE();
        }
    }

    /**
     * 判断设备是否支持低功耗蓝牙
     * @return
     */
    private boolean isSupportBLE(){
        return isSupportBLE;
    }

//    private void getRemoteDivicesDefault() {
//        final BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
//        if (defaultAdapter==null){
//            //不支持蓝牙
//            return;
//        }
//        if (!defaultAdapter.isEnabled()){
//            //蓝牙没有开启
//            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            context.startActivity(intent);
//            return;
//        }
//
//        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//        context.registerReceiver(mReceiver, filter);
//        defaultAdapter.startDiscovery();
//    }

//    BroadcastReceiver mReceiver = new BroadcastReceiver() {
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//
//                MyLogger.jLog().i("传统蓝牙扫描，name："+device.getName()+"，address："+device.getAddress());
//            }
//        }
//    };


    private void scanDevicesBLE() {
        final BluetoothManager bluetoothManager =
                (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            context.startActivity(enableBtIntent);
            return;
        }

        timmerSubscription = Observable.timer(10, TimeUnit.SECONDS).subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                isScanning = false;
                MyLogger.jLog().i("自动停止扫描");
                behaviorSubject.onCompleted();
            }
        });

        isScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    }

    BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
            MyLogger.jLog().i("低功耗蓝牙扫描，name："+bluetoothDevice.getName()+"，address："+bluetoothDevice.getAddress());
            behaviorSubject.onNext(bluetoothDevice);
        }
    };


}
